package com.simtop.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.pojo.Sqsy;
import com.simtop.pojo.User;
import com.simtop.pojo.Xt;
import com.simtop.pojo.experiment.Experiment;
import com.simtop.pojo.experiment.ExperimentDynamicVo;
import com.simtop.pojo.experiment.ExperimentReportVo;
import com.simtop.service.ExperimentService;
import com.simtop.service.impl.SqyxBaseServerImpl;
import com.simtop.util.JwtUtil;
import com.simtop.vo.ExcelVo;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lvyongwei
 */
//@CrossOrigin
@RestController
@RequestMapping("/experiment")
public class ExperimentController {

    @Autowired
    private ExperimentService experimentService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SqyxBaseServerImpl sqyxBaseServer;

    /**
     * 点赞存储的键名
     */
    private static final String KEY = "editorCheck:giveLike:";


    /**
     * 提交成绩
     * @param experiment
     * @param request
     * @return
     */
    @PostMapping("/add")
    public ServerResponse add(@RequestBody Experiment experiment, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            experiment.setUserId(u.getId());
            boolean flag = experimentService.insertExperiment(experiment);
            if(flag==false){
                return ServerResponse.createByErrorMsg("提交内容失败");
            }
            return ServerResponse.createBySuccessMsg("提交内容成功");
        } catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("提交内容失败");
        }
    }

    /**
     * 修改提交内容
     * @param experiment
     * @param request
     * @return
     */
    @PostMapping("/update")
    public ServerResponse update(@RequestBody Experiment experiment, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            experimentService.updateExperiment(experiment);
            return ServerResponse.createBySuccessMsg("修改成绩成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("修改成绩失败");
        }
    }

    /**
     * 查看实验动态(即每个人都能看到其他所有人)
     * @param experimentDynamicVo
     * @param request
     * @return
     */
    @PostMapping("/getDynamic")
    public ServerResponse getDynamic(@RequestBody ExperimentDynamicVo experimentDynamicVo, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            PageHelper.startPage(experimentDynamicVo.getPageNum(),experimentDynamicVo.getPageSize());
            List<ExperimentDynamicVo> allDynamic = experimentService.getAllDynamic(experimentDynamicVo.getMessage());
            allDynamic.forEach(
                    a -> {
                        a.setGiveLike(redisTemplate.opsForSet().size(KEY + a.getExperimentId()));
                        a.setIfGiveLike(redisTemplate.opsForSet().isMember(KEY + a.getExperimentId(),u.getId()));
                    }
            );
            PageInfo<ExperimentDynamicVo> pageInfo = new PageInfo<>(allDynamic);
            return ServerResponse.createBySuccess("获取动态成功",pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("获取动态失败");
        }
    }


    /**
     * 查看实验报告列表
     * @param experimentDynamicVo
     * @param request
     * @return
     */
    @PostMapping("/getReport")
    public ServerResponse getReport(@RequestBody ExperimentDynamicVo experimentDynamicVo, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            //判断不是管理员和教师身份
            if (!u.getRoleId().equals(1) && !u.getRoleId().equals(2)) {
                PageHelper.startPage(experimentDynamicVo.getPageNum(),experimentDynamicVo.getPageSize());
                List<ExperimentReportVo> allReport = experimentService.getAllReport(u.getId(),experimentDynamicVo.getMessage());
                PageInfo<ExperimentReportVo> pageInfo = new PageInfo<ExperimentReportVo>(allReport);
                return ServerResponse.createBySuccess("获取实验报告成功",pageInfo);
            }
            PageHelper.startPage(experimentDynamicVo.getPageNum(),experimentDynamicVo.getPageSize());
            List<ExperimentReportVo> allReport = experimentService.getAllReport(null,experimentDynamicVo.getMessage());
            PageInfo<ExperimentReportVo> pageInfo = new PageInfo<ExperimentReportVo>(allReport);
            return ServerResponse.createBySuccess("获取实验报告成功",pageInfo);
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("获取实验报告成功");
        }
    }

    /**
     * 查看实验报告
     * @param
     * @param
     * @return
     */
    @PostMapping("/gitallsy")
    public ServerResponse gitallsy(@RequestBody ExperimentDynamicVo experimentDynamicVo, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        //System.out.println(u.getId());findExperimental
        //System.out.println(u.getRoleId());

            //判断不是管理员和教师身份
            if (u.getRoleId().equals(10) && u.getRoleId().equals(20)) {
                PageHelper.startPage(experimentDynamicVo.getPageNum(),experimentDynamicVo.getPageSize());
                //只找自己\
                System.out.println(u.getId());
                List<Sqsy> allsy = sqyxBaseServer.allsy(u.getId());
                for (Sqsy as:allsy
                     ) {
                    String markinfo = as.getMarkinfo();
                    String markinfoss = markinfo.substring(1, markinfo.length() - 1);
                    String[] aa = markinfoss.split(",");
                    as.setLastmarkinfo(aa);

                }

                PageInfo<Sqsy> pageInfo = new PageInfo<Sqsy>(allsy);
                return ServerResponse.createBySuccess("获取实验报告成功",pageInfo);
            }
            PageHelper.startPage(experimentDynamicVo.getPageNum(),experimentDynamicVo.getPageSize());
            //List<ExperimentReportVo> allReport = experimentService.getAllReport(null,experimentDynamicVo.getMessage());

            //全查
            List<Sqsy> allallsy = sqyxBaseServer.allallsy();
        for (Sqsy as:allallsy
        ) {
            String markinfo = as.getMarkinfo();
            String markinfoss = markinfo.substring(1, markinfo.length() - 1);
            String[] aa = markinfoss.split(",");
            as.setLastmarkinfo(aa);

        }


            PageInfo<Sqsy> pageInfo = new PageInfo<Sqsy>(allallsy);
            return ServerResponse.createBySuccess("获取实验报告成功",pageInfo);

    }

    @PostMapping("/tjsy")
    public ServerResponse tjsy(@RequestBody String data, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        //System.out.println(u.getId());
        //System.out.println(u.getRoleId());

            String sqsyname = u.getUsername();
            Integer sqsyuserid = u.getId();
            JSONObject jsonObject = JSON.parseObject(data);

        JSONArray sqmarkinfo = jsonObject.getJSONArray("sqmarkinfo");
        String markinfo = String.valueOf(sqmarkinfo);
        double sqsycj = jsonObject.getDouble("sqsycj");
            Date sqsytimes = jsonObject.getDate("sqsytime");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String sqsytime = sdf.format(sqsytimes);
            String sqsypj = jsonObject.getString("sqsypj");
            String sqsysc = jsonObject.getString("sqsysc");
            String evaluate = jsonObject.getString("evaluate");


            sqyxBaseServer.tjsy(sqsyname,sqsyuserid,sqsycj,sqsytime,sqsypj,sqsysc,markinfo,evaluate);

            return ServerResponse.createBySuccess("提交成功");

    }

    @RequestMapping(value = "ininexper",method = RequestMethod.GET)
    public ServerResponse ininexper(String sqsyid, HttpServletRequest  request , HttpServletResponse response) {



        try {

            if(sqsyid == null){
                try {
                System.out.println("西夏哈哈");
                //找到所有的学生
                List<Sqsy> findAll = sqyxBaseServer.findAllUserList1();

                ArrayList<ExcelVo> excelVos = new ArrayList<>();
                    for (Sqsy as:findAll
                    ) {
                        String markinfo = as.getMarkinfo();
                        String[] mark     =   markinfo.substring(1,markinfo.length()-1).split(",");





                        ExcelVo excelVo = new ExcelVo();
                        excelVo.setName( as.getSqsyname());
                        excelVo.setSycj(as.getSqsycj() );
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format = sdf.format(as.getSqsytime());
                        excelVo.setSytime(format);
                        excelVo.setSypj(as.getSqsypj());
                        excelVo.setSytimes(as.getSqsysc());

                        excelVo.setP1(mark[0]);
                        excelVo.setP2(mark[1]);
                        excelVo.setP3(mark[2]);
                        excelVo.setP4(mark[3]);
                        excelVo.setP5(mark[4]);
                        excelVo.setP6(mark[5]);
                        excelVo.setP7(mark[6]);
                        excelVo.setP8(mark[7]);
                        excelVo.setP9(mark[8]);
                        excelVo.setP10(mark[9]);
                        excelVo.setP11(mark[10]);
                        excelVo.setP12(mark[11]);
                        excelVo.setP13(mark[12]);
                        excelVo.setP14(mark[13]);
                        excelVo.setP15(mark[14]);
                        excelVo.setP16(mark[15]);
                        excelVo.setP17(mark[16]);
                        excelVo.setP18(mark[17]);

                        excelVos.add(excelVo);

                    }


                    ExportParams exportParams = new ExportParams("社群全部成绩数据", "社群全部成绩数据");//设置sheet
                    Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ExcelVo.class, excelVos);//问好处填vo
                    //String fileName = new String("社群全部成绩数据".getBytes(), "UTF-8") + ".xls";//设置excel的名称后缀
                    //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
                    //response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置响应头
                    //response.setCharacterEncoding("UTF-8");//格式
                    String exportFileName ="社群全部用户成绩.xlsx";
                    String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
                    response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);

                    //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
                    response.setContentType("application/vnd.ms-excel");
                    OutputStream os = response.getOutputStream();

                    workbook.write(os);//写入
                    os.flush();


                    try {
                        os.close();//关闭
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return ServerResponse.createBySuccess();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return ServerResponse.createByError();
                }



            }


            System.out.println(sqsyid);
            String[] split = sqsyid.split(",");

            ArrayList<Integer> objects = new ArrayList<>();
            Arrays.stream(split).iterator();



        ArrayList<Integer> sqsyidlist = new ArrayList<>();


        Iterator<String> iterator = Arrays.stream(split).iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            Integer i = Integer.valueOf(next);
            sqsyidlist.add(i);

            // apiService.finOne
        }

        for (Integer asa:sqsyidlist
             ) {
            System.out.println(asa);
        }

        ArrayList<ExcelVo> excelVos = new ArrayList<>();

        List<Sqsy> findAll = sqyxBaseServer.findAllUserList(sqsyidlist);
        for (Sqsy as:findAll
             ) {
            String markinfo = as.getMarkinfo();
            String[] mark     =   markinfo.substring(1,markinfo.length()-1).split(",");





            ExcelVo excelVo = new ExcelVo();
            excelVo.setName( as.getSqsyname());
            excelVo.setSycj(as.getSqsycj() );
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(as.getSqsytime());
            excelVo.setSytime(format);
            excelVo.setSypj(as.getSqsypj());
            excelVo.setSytimes(as.getSqsysc());

            excelVo.setP1(mark[0]);
            excelVo.setP2(mark[1]);
            excelVo.setP3(mark[2]);
            excelVo.setP4(mark[3]);
            excelVo.setP5(mark[4]);
            excelVo.setP6(mark[5]);
            excelVo.setP7(mark[6]);
            excelVo.setP8(mark[7]);
            excelVo.setP9(mark[8]);
            excelVo.setP10(mark[9]);
            excelVo.setP11(mark[10]);
            excelVo.setP12(mark[11]);
            excelVo.setP13(mark[12]);
            excelVo.setP14(mark[13]);
            excelVo.setP15(mark[14]);
            excelVo.setP16(mark[15]);
            excelVo.setP17(mark[16]);
            excelVo.setP18(mark[17]);

            excelVos.add(excelVo);

        }


            ExportParams exportParams = new ExportParams("社群成绩数据", "社群成绩数据");//设置sheet
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ExcelVo.class, excelVos);//问好处填vo
            //String fileName = new String("社群成绩".getBytes(), "ISO8859-1") + ".xls";//设置excel的名称后缀
            //String fileNames = "社群用户成绩.xls";
           // fileNames= new String((fileNames).getBytes(), "UTF-8");
            String exportFileName ="社群用户成绩.xlsx";
            String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);

            //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
            response.setContentType("application/vnd.ms-excel");
            //response.setHeader("Content-Disposition", "attachment;filename=" + fileNames);//设置响应头
            //response.setCharacterEncoding("UTF-8");//格式
            OutputStream os = response.getOutputStream();

            workbook.write(os);//写入
            os.flush();
            /**flush指的刷新此输出流并强制写出所有缓冲的输出字节。 flush 的常规协定是：如果此输出流的实现已经缓冲了以前写入的任何字节，则调用此方法指示应将这些字节立即写入它们预期的目标。
             如果此流的预期目标是由基础操作系统提供的一个抽象（如一个文件），则刷新此流只能保证将以前写入到流的字节传递给操作系统进行写入，但不保证能将这些字节实际写入到物理设备（如磁盘驱动器）。**/
            try {
                os.close();//关闭
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ServerResponse.createBySuccess();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ServerResponse.createByError();
        }



    }


    /**
     * 删除实验报告
     * @param
     * @param
     * @return
     */
    @PostMapping("/deletesy")
    public ServerResponse deletesy(@RequestBody String data, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        //System.out.println(u.getId());
        //System.out.println(u.getRoleId());
        try{
            JSONObject jsonObject = JSON.parseObject(data);
            int sqsyid = jsonObject.getInteger("sqsyid");
            sqyxBaseServer.deletesy(sqsyid);

            return ServerResponse.createBySuccess("删除成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("删除实验报告失败");
        }
    }


    /**
     * 提交实验报告
     * @param
     * @param
     * @return
     */
    @PostMapping("/insertsy")
    public ServerResponse insertsy(@RequestBody Sqsy  sqsy, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        //System.out.println(u.getId());
        //System.out.println(u.getRoleId());
        try{
            int sqsyuserid = u.getId();
            String sqsyname = u.getUsername();
            String sqsysc = sqsy.getSqsysc();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date sqsytimes = sqsy.getSqsytime();
            String sqsytime = sdf.format(sqsytimes);
            double sqsycj= sqsy.getSqsycj();
            String sqsypj = sqsy.getSqsypj();
            sqyxBaseServer.insertsy(sqsyuserid,sqsyname,sqsysc,sqsytime,sqsycj,sqsypj);

            return ServerResponse.createBySuccess("提交实验报告成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("提交实验报告失败");
        }
    }



        /**
         * 点赞
         */
    @PostMapping("/giveLike")
    public ServerResponse giveLike(@RequestBody String data,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject jsonObject = JSONObject.parseObject(data);
            Long id = jsonObject.getLong("experimentId");
            redisTemplate.opsForSet().add(KEY + id,u.getId());
            return ServerResponse.createBySuccessMsg("点赞成功");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("点赞失败");
        }
    }


    /**
     * 删除实验报告
     */
    @PostMapping("/delete")
    public ServerResponse delete(@RequestBody String data,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject jsonObject = JSONObject.parseObject(data);
            Long id = jsonObject.getLong("experimentId");
            experimentService.delete(id);
            return ServerResponse.createBySuccessMsg("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("删除失败");
        }
    }
    //展示习题
    @PostMapping("/xtshow")
    public ServerResponse xtshow(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }



            List<Xt> xtshow = experimentService.xtshow();
        for (Xt as:xtshow
             ) {
            String xtda = as.getXtda();
            JSONArray jsonObject = (JSONArray) JSONArray.parse(xtda);
            as.setLast(jsonObject);
        }
            return ServerResponse.createBySuccess("获取成功",xtshow);

        }


    @PostMapping("/xtupdate")
    public ServerResponse xtupdate(@RequestBody Xt xt,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        if(!(u.getRoleId() == 1) && !(u.getRoleId() == 2)){
            return ServerResponse.createByErrorMsg("无权限");
        }

        int xtid = xt.getXtid();
        String xttitle = xt.getXttitle();
        String xttype = xt.getXttype();
        String xtonly = xt.getXtonly();
        JSONArray last = xt.getLast();
        String xtda = String.valueOf(last);
        experimentService.xtupdate(xtid,xttitle,xttype,xtonly,xtda);



        return ServerResponse.createBySuccess("修改成功");

    }

    @PostMapping("/tjpage")
    public ServerResponse tjpage(MultipartFile filename, HttpServletRequest request) {
        try {
        String uploadPath = "C:\\webProject\\Java\\sqyxmage";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        String OriginalFilename = filename.getOriginalFilename();//获取原文件名
        String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名
        String  sfile= OriginalFilename  +suffixName;
        File localFile = new File(uploadPath+"\\"+sfile);

            filename.transferTo(localFile); //把上传的文件保存至本地


        } catch (Exception e) {
            e.printStackTrace();
        }


        return ServerResponse.createBySuccess("上传成功");

    }



}